package com.gamemost.entity;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.gamemost.managers.ResourcesManager;
import com.gamemost.templestay.Config;
import com.gamemost.templestay.DownloadImageService;
import com.gamemost.templestay.MainActivity;
import com.gamemost.templestay.R;

import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

public class JSONParser {
	static InputStream is = null;
	static JSONArray jarray = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}

	public String loadJSonData(String url) throws ClientProtocolException, IOException {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e("==>", "Failed to download file");
			}
		
		return builder.toString();
	}

	public boolean getListBookStand(String url, ArrayList<BookStand> arrayList) {
		String text = "";
		try {
			text = loadJSonData(url);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		// System.out.println("getListBookStand+"+text);
		if (!text.equals("{}")) {
			BookStand aBookStand;
			try {
				JSONObject jObject = new JSONObject(text);
				Iterator childObject = jObject.keys();
				while (childObject.hasNext()) {
					JSONArray jArray = jObject.getJSONArray(childObject.next()
							.toString());
					for (int i = 0; i < jArray.length(); i++) {

						aBookStand = new BookStand();
						JSONObject aObject = jArray.getJSONObject(i);
						setAttribute(aBookStand, BookStand.TAG_BOOK_COUNT,
								aObject);
						setAttribute(aBookStand, BookStand.TAG_FOLDER_ID,
								aObject);
						setAttribute(aBookStand, BookStand.TAG_FOLDER_IMAGE,
								aObject);
						setAttribute(aBookStand, BookStand.TAG_FOLDER_NAME,
								aObject);
						setAttribute(aBookStand, BookStand.TAG_FOLDER_TIME,
								aObject);
						setAttribute(aBookStand, BookStand.TAG_USER_ID, aObject);
						setAttribute(aBookStand, BookStand.TAG_IMAGES, aObject);
						aBookStand.setTitle(aBookStand
								.get(BookStand.TAG_FOLDER_NAME));
						aBookStand.setId(aBookStand
								.get(BookStand.TAG_FOLDER_ID));
						if (aBookStand.get(BookStand.TAG_FOLDER_ID) != null) {
							arrayList.add(aBookStand);
						}

					}
				}
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
				return false;
			}
		}
		ResourcesManager.ac.firtcount2++;
		return true;
		// return JSON String
	}

	public boolean getListBookRecent(String url, final ArrayList<BookRecent> list,
			int typebook) {
		String text = "";
		try {
			text = loadJSonData(url);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		System.out.println("getListBookRecent start " + text);
		if (!text.equals("{}")) {
			BookRecent aBookRecent;
			try {
				JSONObject jObject = new JSONObject(text);
				Iterator childObject = jObject.keys();

				while (childObject.hasNext()) {
					JSONArray jArray = jObject.getJSONArray(childObject.next()
							.toString());
					for (int i = 0; i < jArray.length(); i++) {
						aBookRecent = new BookRecent();
						JSONObject aObject = jArray.getJSONObject(i);
						setAttribute(aBookRecent, BookRecent.TAG_BOOK_FOLDER,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_VERSION,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_PUBLISHER,
								aObject);
						setAttribute(aBookRecent, BookRecent.TA_BOOK_CONFIG,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_VISITED_COUNT,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_LANGUAGE_ID,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_TITLE, aObject);
						setAttribute(aBookRecent, BookRecent.TAG_CREATE_DATE,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_DESCRIPTION,
								aObject);
						setAttribute(aBookRecent,
								BookRecent.TAG_MODIFY_AUTHOR_ID, aObject);
						setAttribute(aBookRecent, BookRecent.TAG_AUTHOR_NAME,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_AUTHOR_ID,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_LANGUAGE_NAME,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_WRITER,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_COMMENT_COUNT,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_COPYRIGHTS,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_BOOK_URL,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_BOOK_ID,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_MODIDY_DATE,
								aObject);
						setAttribute(aBookRecent,
								BookRecent.TAG_BOOK_TYPE_NAME, aObject);
						setAttribute(aBookRecent, BookRecent.TAG_BOOK_TOC,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_CATEGORY_ID,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_BOOK_TYPE_ID,
								aObject);
						setAttribute(aBookRecent,
								BookRecent.TAG_MODIFY_AUTHOR_NAME, aObject);
						setAttribute(aBookRecent,
								BookRecent.TAG_BOOK_STATUS_ID, aObject);
						setAttribute(aBookRecent, BookRecent.TAG_BOOK_ISBN,
								aObject);
						setAttribute(aBookRecent,
								BookRecent.TAG_BOOK_STATUS_NAME, aObject);
						setAttribute(aBookRecent, BookRecent.TAG_PRICE, aObject);
						setAttribute(aBookRecent, BookRecent.TAG_CATEGORY_NAME,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_LIKE_COUNT,
								aObject);
						setAttribute(aBookRecent, BookRecent.TAG_BOOK_COVER,
								aObject);
						setAttribute(aBookRecent,
								BookRecent.TAG_AUTHOR_PORTRAIT, aObject);
						setAttribute(aBookRecent, BookRecent.TAG_IDENTIFIER,
								aObject);
						aBookRecent.setId(aBookRecent
								.get(BookRecent.TAG_BOOK_ID));
						aBookRecent.setTitle(aBookRecent
								.get(BookRecent.TAG_TITLE));
						aBookRecent.setCategoryId(aBookRecent
								.get(BookRecent.TAG_CATEGORY_ID));
						aBookRecent.setUrl(aBookRecent
								.get(BookRecent.TAG_BOOK_URL));
						aBookRecent.setBookcover(aBookRecent
								.get(BookRecent.TAG_BOOK_COVER));
						aBookRecent.setTypeBook(Integer.parseInt(aBookRecent
								.get(BookRecent.TAG_BOOK_TYPE_ID)));
					
						if (aBookRecent.getTypeBook() != 1 && 
								aBookRecent.getTypeBook() != 2) {
							System.out.println("invalid id book "+aBookRecent.getTypeBook());
						}
						int indexDownloaded = checkExistBook(aBookRecent);
						System.out.println(indexDownloaded
								+ " index downloaded ");
						if (typebook == 0) {
							if (indexDownloaded == -1) {
								list.add(aBookRecent);

							}
						} else if (typebook == 1) {
							if (indexDownloaded == -1) {
								list.add(aBookRecent);
							} else {
								// add book tai vi tri i cua listdowloadbook
								// vaof
								// list book in book stand
								DownloadedBook dlb = ResourcesManager.ac.listDownloadedBook
										.get(indexDownloaded);
								ResourcesManager.ac.listDownloadedBookInListBookStand.add(dlb);
								BookRecent br = new BookRecent();
								br.hasDownload = true;
								br.setFilename(dlb.getFilename());
								br.setId(dlb.getId());
								br.setImage(dlb.getImage());
								br.setTypeBook(dlb.getTypeBook());
								if (br.getTypeBook() == Config.FIX_LAYOUT) {
									br.setBookmark(dlb.getBookmarkString());
								} else {
									br.setBookmark(dlb.getStringBMReflow());
								}
								br.setBookcover(dlb.getBookcover());
								br.setTitle(dlb.getTitle());
								br.setUrl(dlb.getUrl());
								br.setCategoryId(dlb.getCategoryId());
								System.out.println("aaa");
								String imagePath = Environment
										.getExternalStorageDirectory()
										.toString()
										+ Config.IMAGE_BOOK
										+ "/"
										+ br.getImage();
								File f = new File(imagePath);
								Bitmap bitmap = DownloadImageService
										.decodeFile(f);
								Bitmap bmp = Bitmap.createScaledBitmap(bitmap,
										ResourcesManager.ac.width / 5,
										ResourcesManager.ac.height / 6, true);
								if (bitmap != null) {
									bmp = Bitmap.createScaledBitmap(bitmap,
											ResourcesManager.ac.width / 5,
											ResourcesManager.ac.height / 6,
											true);
								} else {
									Drawable drawable = ResourcesManager.ac
											.getResources().getDrawable(
													R.drawable.no_book_cover);
									if (drawable instanceof BitmapDrawable) {
										dlb.setBitmap(Bitmap
												.createScaledBitmap(
														((BitmapDrawable) drawable)
																.getBitmap(),
														ResourcesManager.ac.width / 5,
														ResourcesManager.ac.height / 6,
														true));
									}
								}
								br.setBitmap(bmp);
								int startIndex = 0;

								if (!list.isEmpty()) {
									startIndex = ResourcesManager.ac
											.getPosMinNotBookDownload(list);
								}
								list.add(br);
								if (startIndex != -1)
									Collections.swap(list, startIndex,
											list.size() - 1);
								count++;
								// size curent of book in book stand
								MainActivity.sizeListbookInBookStand = count;
							}
						}
						System.out.println("size downloadedbookstand "+	ResourcesManager.ac.listDownloadedBookInListBookStand.size());
					}
				}
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
				return false;
			}
		}
		return true;

	}

	public int count = 0;

	public static int checkExistBook(BookRecent book) {
		if (!ResourcesManager.ac.listDownloadedBook.isEmpty()) {
			for (int i = 0; i < ResourcesManager.ac.listDownloadedBook.size(); i++) {
				if (book.getId() != null) {
					if (book.getId().equals(
							ResourcesManager.ac.listDownloadedBook.get(i)
									.getId())) {
						return i;
					}
				}
			}
		}
		return -1;
	}

	public boolean getListSubCategory(String url,
			ArrayList<SubCategory> listSubCategory) {
		String text;
		try {
			text = loadJSonData(url);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		// System.out.println("text subcategory "+text);
		SubCategory aSubCategory;
		try {
			JSONObject jObject = new JSONObject(text);
			Iterator childObject = jObject.keys();

			while (childObject.hasNext()) {
				JSONArray jArray = jObject.getJSONArray(childObject.next()
						.toString());
				// System.out.println("text subcategory jArray.length() "+jArray.length());

				for (int i = 0; i < jArray.length(); i++) {
					aSubCategory = new SubCategory();
					JSONObject aObject = jArray.getJSONObject(i);
					setAttribute(aSubCategory, SubCategory.TAG_CC_ID, aObject);
					setAttribute(aSubCategory, SubCategory.TAG_CC_CREATETIME,
							aObject);
					setAttribute(aSubCategory, SubCategory.TAG_CC_NAME, aObject);
					setAttribute(aSubCategory, SubCategory.TAG_FOLDER_ID,
							aObject);

					System.out.println(aSubCategory.get(SubCategory.TAG_CC_ID)
							+ " cc id sub category");
					System.out.println(aSubCategory
							.get(SubCategory.TAG_CC_NAME)
							+ " cc name  sub category");
					aSubCategory.setId(aSubCategory.get(SubCategory.TAG_CC_ID));
					if (!checkSubCategory(aSubCategory)) {
						ResourcesManager.ac.listStringSubCategory
								.add(aSubCategory.get(SubCategory.TAG_CC_NAME));
						listSubCategory.add(aSubCategory);
					}
				}
			}
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
			return false;
		}
		
		return true;
	}

	private boolean checkSubCategory(SubCategory sub) {
		// TODO Auto-generated method stub
		if (!ResourcesManager.ac.listSubCategory.isEmpty()) {
			for (int i = 0; i < ResourcesManager.ac.listSubCategory.size(); i++) {
				if (ResourcesManager.ac.listSubCategory.get(i).getId()
						.equals(sub.getId())) {
					return true;
				}
			}
		}
		return false;
	}

	public void setAttribute(BookService aBook, String tag, JSONObject aObject) {
		JSONArray arr = null;
		try {
			arr = aObject.getJSONArray(tag);
			for (int j = 0; j < arr.length(); j++) {
				aBook.put(tag, arr.getString(j));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public boolean getLIstBookSubCategory(String url, ArrayList<BookRecent> list) {
		// TODO Auto-generated method stub
		String text;
		try {
			text = loadJSonData(url);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		// System.out.println("getListBookRecent start "+text);

		BookRecent aBookRecent;
		try {
			JSONObject jObject = new JSONObject(text);
			Iterator childObject = jObject.keys();

			while (childObject.hasNext()) {
				JSONArray jArray = jObject.getJSONArray(childObject.next()
						.toString());
				for (int i = 0; i < jArray.length(); i++) {
					aBookRecent = new BookRecent();
					JSONObject aObject = jArray.getJSONObject(i);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_FOLDER,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_VERSION, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_PUBLISHER, aObject);
					setAttribute(aBookRecent, BookRecent.TA_BOOK_CONFIG,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_VISITED_COUNT,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_LANGUAGE_ID,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_TITLE, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_CREATE_DATE,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_DESCRIPTION,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_MODIFY_AUTHOR_ID,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_AUTHOR_NAME,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_AUTHOR_ID, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_LANGUAGE_NAME,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_WRITER, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_COMMENT_COUNT,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_COPYRIGHTS,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_URL, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_ID, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_MODIDY_DATE,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_TYPE_NAME,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_TOC, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_CATEGORY_ID,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_TYPE_ID,
							aObject);
					setAttribute(aBookRecent,
							BookRecent.TAG_MODIFY_AUTHOR_NAME, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_STATUS_ID,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_ISBN, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_STATUS_NAME,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_PRICE, aObject);
					setAttribute(aBookRecent, BookRecent.TAG_CATEGORY_NAME,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_LIKE_COUNT,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_BOOK_COVER,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_AUTHOR_PORTRAIT,
							aObject);
					setAttribute(aBookRecent, BookRecent.TAG_IDENTIFIER,
							aObject);
					aBookRecent.setId(aBookRecent.get(BookRecent.TAG_BOOK_ID));
					aBookRecent.setTitle(aBookRecent.get(BookRecent.TAG_TITLE));
					aBookRecent.setCategoryId(aBookRecent
							.get(BookRecent.TAG_CATEGORY_ID));
					aBookRecent
							.setUrl(aBookRecent.get(BookRecent.TAG_BOOK_URL));
					aBookRecent.setBookcover(aBookRecent
							.get(BookRecent.TAG_BOOK_COVER));
					list.add(aBookRecent);
				}

			}
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
			return false;
		}

		return true;
	}
}
